package v1.chapter6.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * 动态代理
 * @author admin
 *
 */
public class ProxyTest3 {

	public static void main(String[] args) {
		IUserDao target = new UserDao();
		System.out.println(target.getClass());

		IUserDao proxy = (IUserDao) new ProxyFactory(target).getProxyInstance();
		System.out.println(proxy.getClass());

		proxy.save();
	}

}

class ProxyFactory {
	private Object target;

	public ProxyFactory(Object t) {
		target = t;
	}

	public Object getProxyInstance() {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
				new InvocationHandler() {
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						System.out.println("开始事务……");
						Object returnValue = method.invoke(target, args);
						System.out.println("提交事务……");
						return returnValue;
					}
				});
	};
}
